package com.zx.chatroom.listener;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.corundumstudio.socketio.annotation.OnJsonObject;
import com.zx.chatroom.po.ScoreInfo;
import com.zx.chatroom.server.SocketServer;
import com.zx.chatroom.service.LoginService;
import com.zx.chatroom.util.LogUtil;
import com.zx.chatroom.vo.Chat;
import com.zx.chatroom.vo.UserVo;
import com.zx.framework.core.util.DateTimeUtil;
import com.zx.framework.core.util.FileUtil;
import com.zx.framework.core.util.SequenceUtil;
import com.zx.framework.core.util.SpringBeanUtil;
import com.zx.framework.core.util.StringUtil;

public class HallListener extends BaseListener{
	private static HallListener instance;
	private HallListener() {
	}
	public static HallListener getInstance() {
		if (instance == null) {
			synchronized (HallListener.class) {
				if (instance == null) {
					instance = new HallListener();
				}
			}
		}
		return instance;
	}
	private static final Logger LOGGER = Logger.getLogger(HallListener.class);
	
	/**
	 * 所有用户信息
	 * put(userid,userVo);
	 */
	public static Map<String, UserVo> USER_LIST = new Hashtable<String, UserVo>();
	
	/**
	 * 所有登陆到大厅的用户
	 * put(userid,userVo);离开移除
	 */
	private static Map<String, UserVo> ONLINE_USER = new Hashtable<String, UserVo>();
	
	/**
	 * 通讯关系
	 * put(营业员ID,坐席ID);
	 */
	private static Map<String, String> VISIT_SEAT = new Hashtable<String, String>();
	
	/**
	 * 保存用户SOCKET
	 * put(userId,SocketIOClient);
	 */
	private static Map<String, SocketIOClient> USER_SOCKET = new Hashtable<String, SocketIOClient>();
	
	/**
	 * sessionid和userid的关系,离开移除
	 * put(client.getSessionId(),userid);
	 */
	private static Map<String, String> SESSIONID_USER = new Hashtable<String, String>();
	
	/**
	 * 用户在线时间
	 * userid和data.getTime()
	 * pub(userid,times);
	 */
	private static Map<String, Long> USER_ONLINE_TIME = new Hashtable<String, Long>();
	
	@OnConnect
	public void onConnect(SocketIOClient client) {
		LOGGER.info(client.getSessionId()+"进入大厅！");
	}

	@OnDisconnect
	public void onDisconnect(SocketIOClient client) {
		try{
			LOGGER.info(client.getSessionId()+"离开大厅！");
			String userId = SESSIONID_USER.get(client.getSessionId().toString());
			if (StringUtil.isNotEmpty(userId)) {
				UserVo userVo = findOnlineUserByUserId(userId);
				if (null != userVo) {
					userLeave(userVo.getId(),client.getSessionId().toString());
					removeUserToList(client, userVo);
				}
			}
		}catch(Exception e){
			LOGGER.error(e);
		}
	}
	
	/**
	 * 用户进入大厅，保存用户信息
	 * @param userId
	 * @param jobCode
	 * @param client
	 */
	@OnEvent(value="connChatRoom")
	public void connChatRoom(String userId,String jobCode,SocketIOClient client){
		if (USER_SOCKET.containsKey(userId)) {
			SocketIOClient earlyClient =  findSocketByUserId(userId);
			earlyClient.sendEvent("leaveInfo", "您已在其它地方登录，被迫下线.");
			earlyClient.disconnect();
			
		}
		UserVo userVo = findLoginUserByUserId(userId);
		ONLINE_USER.put(userId, userVo);
		SESSIONID_USER.put(client.getSessionId().toString(), userId);
		USER_SOCKET.put(userId, client);
		// 设置在线
		userVo.setStatus(ONLINE);
		// 加入职位代码
		userVo.setJobCode(jobCode);
		addUserToList(client, userVo);
		// 进入大厅返回全部用户
		client.sendEvent("userList", gson.toJson(ONLINE_USER));
		if (jobCode.equals(VISIT)) {//只记录营业员
			//记录用户在线时间
			USER_ONLINE_TIME.put(userId, new Date().getTime());
		}
	}
	
	/**
	 * 建立通讯联系
	 */
	@OnEvent(value="createContact")
	public void createContact(String toUser,String fromUser,SocketIOClient client){
		if (StringUtil.isNotEmpty(fromUser)) {
			UserVo userVo = ONLINE_USER.get(fromUser);
			if (null != userVo) {
				client.sendEvent("createContact", gson.toJson(userVo));
				//通讯关系是否存在
				if (!VISIT_SEAT.containsKey(fromUser) && !VISIT_SEAT.containsValue(fromUser)) {
					//设置忙碌状态
					ONLINE_USER.get(fromUser).setStatus(BUSY);
				}
			}
		}
	}
	
	/**
	 * 营业员请求连接客服
	 * @param visitId
	 * @param seatId
	 * @param client
	 */
	@OnEvent(value="visitRequestConnect")
	private void visitRequestConnect(String visitId,String seatId,SocketIOClient client){
		if(StringUtil.isEmpty(seatId)||StringUtil.isEmpty(visitId)){
			client.sendEvent("errorMsg", "请求连接失败，请稍后再试！info[visitRequestConnect]");
			LOGGER.error("坐席ID或营业员ID不能为空！");
		}
		SocketIOClient seatClient = findSocketByUserId(seatId);
		if(seatClient!=null){
			seatClient.sendEvent("visitRequest", visitId);
		}
	}
	
	/**
	 * 坐席应答营业员
	 * @param visitId
	 * @param seatId
	 * @param client
	 */
	@OnEvent(value="seatResponseVisit")
	public void seatResponseVisit(String seatId,String visitId,SocketIOClient client){
		//坐席应答后，给营业员发送坐席信息
		SocketIOClient visitClient = findSocketByUserId(visitId);
		UserVo seatUserVo = findLoginUserByUserId(seatId);
		visitClient.sendEvent("seatResponse", gson.toJson(seatUserVo));
		//坐席应答后，给坐席发送营业员信息
		SocketIOClient seatClient = findSocketByUserId(seatId);
		UserVo visitUserVo = findLoginUserByUserId(visitId);
		seatClient.sendEvent("visitInfo", gson.toJson(visitUserVo));
		VISIT_SEAT.put(visitId, seatId);
		List<Map.Entry<String, String>> nexusList = findNexusByUserId(seatId);
		visitClient.getNamespace().getBroadcastOperations().sendEvent("seatSize", "{'seatId':'"+seatId+"','size':'"+nexusList.size()+"'}");
	}

	/**
	 * 页面人员列表增加,单个人员
	 * @param client
	 * @param userId
	 * @param jobCode
	 */
	private void addUserToList(SocketIOClient client,UserVo userVo) {
		userVo.setDate(DateTimeUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm"));
		client.getNamespace().getBroadcastOperations().sendEvent("addUserToList", gson.toJson(userVo));
		client.getNamespace().getBroadcastOperations().sendEvent("userCount", ONLINE_USER.size());
	}
	/**
	 * 页面人员列表删除
	 * @param client
	 * @param userId
	 */
	private void removeUserToList(SocketIOClient client,UserVo userVo) {
		userVo.setDate(DateTimeUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm"));
		client.getNamespace().getBroadcastOperations().sendEvent("removeUserToList", gson.toJson(userVo));
		client.getNamespace().getBroadcastOperations().sendEvent("userCount", ONLINE_USER.size());
	}
	/**
	 * 获得登陆用户信息
	 * @param userId
	 * @return
	 */
	private UserVo findLoginUserByUserId(String userId){
		if (USER_LIST.containsKey(userId)) {
			return USER_LIST.get(userId);
		}
		return null;
	}
	/**
	 * 获得在线用户信息
	 * @param userId
	 * @return
	 */
	public static UserVo findOnlineUserByUserId(String userId){
		if (ONLINE_USER.containsKey(userId)) {
			return ONLINE_USER.get(userId);
		}
		return null;
	}
	/**
	 * 获取用户Socket
	 * @param userId
	 * @return
	 */
	public static SocketIOClient findSocketByUserId(String userId){
		if (USER_SOCKET.containsKey(userId)) {
			return USER_SOCKET.get(userId);
		}
		return null;
	}
	
	/**
	 * 获取用户对应关系
	 * @param userId
	 * @return
	 */
	private static List<Map.Entry<String, String>> findNexusByUserId(String userId){
		List<Map.Entry<String, String>> nexusList = new ArrayList<Map.Entry<String, String>>();
		for (Iterator<Map.Entry<String, String>> keys = VISIT_SEAT.entrySet().iterator(); keys.hasNext();) {
			Map.Entry<String, String> entry =(Map.Entry<String, String>)keys.next();
			if (entry.getKey().equals(userId)) {
				nexusList.add(entry);
				break;
			}
			if (entry.getValue().equals(userId)) {
				nexusList.add(entry);
			}
		}
		return nexusList;
	}
	
	/**
	 * 用户离开
	 * @param userId
	 */
	private void userLeave(String userId,String sessionId){
//		for (Iterator<Map.Entry<String, String>> keys = VISIT_SEAT.entrySet().iterator(); keys.hasNext();) {
//			Map.Entry<String, String> entry =(Map.Entry<String, String>)keys.next();
//			if (entry.getKey().equals(userId)) {
//				userLeaveMessage(entry.getKey());
				//keys.remove();
//				break;
//			}
//			if (entry.getValue().equals(userId)) {
//				userLeaveMessage(entry.getValue());
				//keys.remove();
//			}
//		}
		userLeaveMessage(userId);
		String seatId ="";
		if(VISIT_SEAT!=null && !VISIT_SEAT.isEmpty() && VISIT_SEAT.containsKey(userId)){
			seatId = VISIT_SEAT.get(userId);
			VISIT_SEAT.remove(userId);
			
		}
		List<Map.Entry<String, String>> nexusList = null;
		if(StringUtil.isNotEmpty(seatId)){
			nexusList = findNexusByUserId(seatId);
		}
		SocketIOClient client = findSocketByUserId(userId);
		try{
			if(client!=null&&nexusList!=null){
				client.getNamespace().getBroadcastOperations().sendEvent("seatSize", "{'seatId':'"+seatId+"','size':'"+nexusList.size()+"'}");
			}
		}catch(Exception e){
			LOGGER.error(e);
		}
		SESSIONID_USER.remove(sessionId);
		//USER_LIST.remove(userId);//暂时不移除用户信息list,刷新:进入页面、断开、连接||进入:进入页面、连接
		ONLINE_USER.remove(userId);
		USER_SOCKET.remove(userId);
	}
	/**
	 * 设置用户在线状态
	 */
	private void userLeaveStatus(String sessionId){
		if (StringUtil.isNotEmpty(sessionId)) {
			String userId = SESSIONID_USER.get(sessionId);
			UserVo userVo = ONLINE_USER.get(userId);
			SocketIOClient client = USER_SOCKET.get(userId);
			if (null != userVo && userVo.getStatus() == BUSY && null != client) {
				//坐席：需判断是否有其他通讯关系
				if (userVo.getJobCode().equals(SEAT) && !VISIT_SEAT.containsValue(userId)) {
					ONLINE_USER.get(userId).setStatus(ONLINE);
					//更新列表
					removeUserToList(client, userVo);
					addUserToList(client, ONLINE_USER.get(userId));
				}
				//营业员
				if (userVo.getJobCode().equals(VISIT) && !VISIT_SEAT.containsKey(userId)) {
					ONLINE_USER.get(userId).setStatus(ONLINE);
					//更新列表
					removeUserToList(client, userVo);
					addUserToList(client, ONLINE_USER.get(userId));
				}
			}
		}
	}
	
	/**
	 * 用户离开信息发送
	 * @param userId 离开用户ID
	 */
	private void userLeaveMessage(String userId){
		UserVo leaveUserVo = findOnlineUserByUserId(userId);
		SocketIOClient leaveUserClient = findSocketByUserId(userId);
		if (null == leaveUserVo || null == leaveUserClient) {
			return ;
		}
		SocketIOClient client = null;
		UserVo userKey = null,userValue = null;
		Chat chat = null;
		List<Map.Entry<String, String>> nexusList = findNexusByUserId(userId);
		for (Entry<String, String> entry : nexusList) {
			//营业员
			userKey = findOnlineUserByUserId(entry.getKey());
			//坐席
			userValue = findOnlineUserByUserId(entry.getValue());
			if (null != userKey) {
				if (userKey.getJobCode().equals(VISIT)) {
					//坐席socket
					client = findSocketByUserId(entry.getValue());
					if (null != client) {
						chat = new Chat();
						chat.setMessage("营业员("+userKey.getUsername()+")已离线！");
						client.sendEvent("userLeaveMessage", gson.toJson(chat));
						//设置用户在线
						userLeaveStatus(client.getSessionId().toString());
					}
				}
			}
			if (null != userValue) {
				if (userValue.getJobCode().equals(SEAT)) {
					//营业员socket
					client = findSocketByUserId(entry.getKey());
					if (null != client) {
						chat = new Chat();
						chat.setMessage("坐席("+userValue.getUsername()+")已离线！");
						client.sendEvent("userLeaveMessage", gson.toJson(chat));
						//设置用户在线
						userLeaveStatus(client.getSessionId().toString());
					}
				}
			}
		}
		//leaveUserClient.disconnect();
	}
	
	/**
	 * 消息广播
	 * @param client
	 * @param msg
	 */
	@OnJsonObject
	public void sendMessage(SocketIOClient client ,final Chat chat){
		if (null !=  chat) {
			if(StringUtil.isEmpty(chat.getFromUserId())||StringUtil.isEmpty(chat.getToUserId())){
				return;
			}
			
			UserVo fromUserVo = findLoginUserByUserId(chat.getFromUserId());
			UserVo toUserVo = findLoginUserByUserId(chat.getToUserId());
			if(fromUserVo == null||toUserVo == null){
				return;
			}
			
			chat.setFromUserName(fromUserVo.getUsername());
			chat.setToUserName(toUserVo.getUsername());

			//消息发送者
			SocketIOClient fromClient = null;
			fromClient = findSocketByUserId(chat.getFromUserId());
			fromClient.sendEvent("receiveMessage", gson.toJson(chat));
			
			//消息接收者
			SocketIOClient toClient = null;
			toClient = findSocketByUserId(chat.getToUserId());
			toClient.sendEvent("receiveMessage", gson.toJson(chat));
			logCharInfo(chat);
			if (fromUserVo.getJobCode().equals(VISIT)) {//只记录营业员
				//记录用户在线时间
				USER_ONLINE_TIME.put(fromUserVo.getId(), new Date().getTime());
			}
			if (toUserVo.getJobCode().equals(VISIT)) {//只记录营业员
				//记录用户在线时间
				USER_ONLINE_TIME.put(toUserVo.getId(), new Date().getTime());
			}
		}
	}
	
//	/**
//	 * 上传后发送附件消息
//	 * @param basePath
//	 * @param fromUser
//	 * @param toUser
//	 * @param msg 消息体
//	 */
//	public void upLoadSendMessage(final String basePath,final ChatObject msg){
//		if (null != msg) {
//			SocketIOClient toUserClient = findSocketByUserId(msg.getToUser());
//			msg.setaHref("<a href=\""+basePath+"login/downl?key="+msg.getKey()+"\">"+msg.getFileName()+"</a>");
//			toUserClient.sendEvent("upLoadSendMessage", gson.toJson(msg));
//			//写入日志
//			logCharInfo(toUserClient, msg);
//		}
//	}
	
	/**
	 * 保存聊天记录
	 * @param client
	 * @param msg
	 */
	@OnEvent(value="logCharInfo")
	public void logCharInfo(final Chat chat){
		LogUtil.logChatInfo(SocketServer.getCharInfoOutPath(), chat.getMessage(), chat.getFromUserId(),chat.getFromUserName(), chat.getToUserId(),chat.getToUserName());
		
	}
	
	/**
	 * 异步加载自动回复信息
	 * @param client
	 */
	@OnEvent(value="autoReply")
	public void autoReply(SocketIOClient client){
		LoginService loginService = SpringBeanUtil.getBean("loginService",LoginService.class);
		client.sendEvent("autoReply", gson.toJson(loginService.getAllAutoReply()));
	}
	/**
	 * 用户离线，给对应人员发送消息
	 * @param client
	 * @param leaveUserId
	 */
	@OnEvent(value = "userIsLeave")
	public void userIsLeave(SocketIOClient client,String leaveUserId){
		List<Map.Entry<String, String>> nexusList = findNexusByUserId(leaveUserId);
		UserVo userKey = null;
		UserVo userValue = null;
		Chat chat = null;
		for (Entry<String, String> entry : nexusList) {
			//营业员
			userKey = findOnlineUserByUserId(entry.getKey());
			//坐席
			userValue = findOnlineUserByUserId(entry.getValue());
			if (null != userKey) {
				if (userKey.getJobCode().equals(VISIT)) {
					//坐席socket
					client = findSocketByUserId(entry.getValue());
					if (null != client) {
						chat = new Chat();
						chat.setMessage("营业员("+userKey.getUsername()+")已离线！");
						client.sendEvent("userLeaveMessage", gson.toJson(chat));
						//设置用户在线
						userLeaveStatus(client.getSessionId().toString());
					}
				}
			}
			if (null != userValue) {
				if (userValue.getJobCode().equals(SEAT)) {
					//营业员socket
					client = findSocketByUserId(entry.getKey());
					if (null != client) {
						chat = new Chat();
						chat.setMessage("坐席("+userValue.getUsername()+")已离线！");
						client.sendEvent("userLeaveMessage", gson.toJson(chat));
						//设置用户在线
						userLeaveStatus(client.getSessionId().toString());
					}
				}
			}
		}
	}
	
	/**
	 * 营业员离开
	 * @param _visitId
	 * @param _seatId
	 * @param client
	 */
	@OnEvent(value="visitIsLeave")
	public void visitIsLeave(String _visitId,String _seatId,SocketIOClient client){
		SocketIOClient seatClient = findSocketByUserId(_seatId);
		UserVo vUser = findLoginUserByUserId(_visitId);
		seatClient.sendEvent("visitLeave", gson.toJson(vUser));
	}

	
	/**
	 * 异步加载评分信息
	 * @param client
	 * @param userId
	 * @param className 需绑定的class值
	 */
	@OnEvent(value="scoreInfo")
	public void scoreInfo(SocketIOClient client,String _visitId,String _seatId){
		SocketIOClient visitClient = findSocketByUserId(_visitId);
		UserVo vUser = findLoginUserByUserId(_visitId);
		UserVo sUser = findLoginUserByUserId(_seatId);
		String className = "evaluationLink";
		if (StringUtil.isNotEmpty(_visitId) && StringUtil.isNotEmpty(className)) {
			UserVo userVo = ONLINE_USER.get(_visitId);
			//只能营业员评分
			if (null != userVo && (userVo.getJobCode().equals(VISIT))) {
				StringBuffer score_str = new StringBuffer("<span style=\"color:red;font-weight: bold;\">请您为本次服务进行评分：</span>");
				for (Map.Entry<String, String> e : SCORE_DATA.entrySet()) {
					score_str.append("<a style=\"color:red;font-weight: bold;text-decoration: underline;\" seatid =\""+_seatId+"\" href = \"#\" class=\""+className+"\" ev=\""+e.getKey()+"\">"+e.getValue()+"</a>&nbsp;&nbsp;");
				}
				if(vUser!=null&&sUser!=null){
					client.sendEvent("scoreInfo", "{'vId':'"+getGson().toJson(vUser)+"','sId':'"+getGson().toJson(sUser)+"','info':'评分信息已发送，请等待营业员评价！'}");
					visitClient.sendEvent("scoreInfo", "{'vId':'"+getGson().toJson(vUser)+"','sId':'"+getGson().toJson(sUser)+"','info':'"+score_str.toString()+"'}");
					 
				}
				
			}
		}
	}
	
	/**
	 * 异步保存评分信息
	 * @param client
	 * @param fromUser
	 * @param toUser
	 * @param sid 评分信息ID
	 * @param score 评分值
	 */
	@OnEvent(value="saveScoreInfo")
	public void saveScoreInfo(SocketIOClient client,String _visitId,String _seatId,String sid,Integer score,String _scoreText){
		UserVo vUser = findLoginUserByUserId(_visitId);
		UserVo sUser = findLoginUserByUserId(_seatId);
		//评分信息更新
		if (StringUtil.isNotEmpty(sid) && null != score && score.intValue() > 0) {
			LoginService loginService = SpringBeanUtil.getBean("loginService",LoginService.class);
			ScoreInfo scoreInfo = loginService.findScoreInfoById(sid);
			if (null != scoreInfo) {
				scoreInfo.setScore(score);
				scoreInfo.setEndtime(new Date());
				loginService.updateScoreInfo(scoreInfo);
			}
			if(vUser!=null&&sUser!=null){
				client.sendEvent("evalSuccess", "{'vId':'"+getGson().toJson(vUser)+"','sId':'"+getGson().toJson(sUser)+"','info':'评价成功,您已自动离线！'}");
				SocketIOClient seatClient = findSocketByUserId(_seatId);
				client.disconnect();
				seatClient.sendEvent("evalSuccess", "{'vId':'"+getGson().toJson(vUser)+"','sId':'"+getGson().toJson(sUser)+"','info':'"+_scoreText+"'}");
			}
		
			return ;
		}
		//首次保存记录
		if (StringUtil.isNotEmpty(_visitId) && StringUtil.isNotEmpty(_seatId)) {
			LoginService loginService = SpringBeanUtil.getBean("loginService",LoginService.class);
			String uuid = SequenceUtil.getUUID();
			ScoreInfo scoreInfo = new ScoreInfo();
			scoreInfo.setId(uuid);
			scoreInfo.setFromuser(_visitId);
			scoreInfo.setTouser(_seatId);
			scoreInfo.setStarttime(new Date());
			loginService.saveScoreInfo(scoreInfo);
			client.sendEvent("ScoreInfoID", uuid);
		}
	}
	/**
	 * 显示历史记录
	 * @param client
	 * @param _visitId
	 * @param _seatId
	 * @param dateStr
	 */
	@OnEvent(value = "historyInfoShow")
	public void historyInfoShow(SocketIOClient client,String _fromUserId,String _toUserId,String dateStr){
		try {
			String path = SocketServer.getCharInfoOutPath()+dateStr+"/"+dateStr+"("+_fromUserId+" TO "+_toUserId+").txt";
			String path2 = SocketServer.getCharInfoOutPath()+dateStr+"/"+dateStr+"("+_toUserId+" TO "+_fromUserId+").txt";
			//String path ="E:/charInfoOutPath/2014-05-26/2014-05-26(admin TO gcwh).txt";
			File f = new File(path);
			File f2 = new File(path2);
			if(f.isFile()){
				String info = FileUtil.readFileToString(f,"utf-8");
				client.sendEvent("hisInfo", info);
			}else if(f2.isFile()){
				String info = FileUtil.readFileToString(f2,"utf-8");
				client.sendEvent("hisInfo", info);
			}else{
				client.sendEvent("hisInfo", "暂无记录");
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 坐席终结营业员
	 * @param client
	 * @param _visitId
	 */
	@OnEvent(value = "seatFinalityVisit")
	public void seatFinalityVisit(SocketIOClient client,String _visitId){
		if (StringUtil.isNotEmpty(_visitId)) {
			
			UserVo userVo = findOnlineUserByUserId(_visitId);
			SocketIOClient _visitIdClient = USER_SOCKET.get(_visitId);
			if (null != userVo && null != _visitIdClient) {
				_visitIdClient.sendEvent("leaveInfo", "系统监测到您长时间未活动,请您下线.");
				userLeave(userVo.getId(),_visitIdClient.getSessionId().toString());
				removeUserToList(_visitIdClient, userVo);
			}
		}
	}
	/**
	 * 转接申请
	 */
	@OnEvent(value = "adapterVisit")
	public void adapterVisit(SocketIOClient client,String _visitId,String _seatId){
		if(StringUtil.isNotEmpty(_visitId)&&StringUtil.isNotEmpty(_seatId)){
			SocketIOClient _visitClient = USER_SOCKET.get(_visitId);
			SocketIOClient _seatClient = USER_SOCKET.get(_seatId);
			//移除之前对应关系
			SocketIOClient expiredClient =null;
			String expiredUserId = VISIT_SEAT.get(_visitId);
			if(StringUtil.isNotEmpty(expiredUserId)){
				expiredClient = USER_SOCKET.get(expiredUserId);
				VISIT_SEAT.remove(_visitId);
			}
			
			
			//put新的对应关系
			VISIT_SEAT.put(_visitId, _seatId);
			ONLINE_USER.get(_visitId).setStatus(BUSY);
			ONLINE_USER.get(_seatId).setStatus(BUSY);
			UserVo visitUserVo = findLoginUserByUserId(_visitId);
			UserVo seatUserVo = findLoginUserByUserId(_seatId);
			_visitClient.sendEvent("adapterMe", gson.toJson(seatUserVo));
			_seatClient.sendEvent("adapterUser", gson.toJson(visitUserVo));
			expiredClient.sendEvent("removeUserLi", _visitId);
		}
	}
	/**
	 * 自动离线用户
	 */
	public void autoOffline(Integer offlineTime){
		Date date = null;
		for (Map.Entry<String, Long> entry : USER_ONLINE_TIME.entrySet()) {
			if (null == date) {
				date = new Date();
			}
			Long offTime = (long) (offlineTime*60*1000);
			if ((date.getTime() - entry.getValue()) >= offTime) {
				UserVo userVo = findOnlineUserByUserId(entry.getKey());
				SocketIOClient client = USER_SOCKET.get(entry.getKey());
				if (null != userVo && null != client) {
					client.sendEvent("leaveInfo", "系统监测到您长时间未活动,您已离线！");
					userLeave(userVo.getId(),client.getSessionId().toString());
					removeUserToList(client, userVo);
					USER_ONLINE_TIME.remove(entry.getKey());
				}
			}
		}
	}
}
